use anyhow::Result;
use sqlx::{Pool, MySql, types};
use chrono;
use std::ops::Sub;

use hyper::{Request, Response, Client, body};
use hyper::client::HttpConnector;

use std::collections::HashMap;

use crate::db;
use crate::miner;
use crate::miner::jobs::SealWork;

pub async fn check_wrong_db_task_record(pool: &Pool<MySql>, client: &Client<HttpConnector>, url: &str, token: &str) -> Result<()> {
    let rsp = miner::jobs::query_jobs_from_miner(client, &url, &token).await?;
    if let Some(e) = rsp.error {
        println!("receive error from miner when query jobs, {:?}", e);
        return Ok(())
    }
    let jobs = rsp.result.unwrap();

    let jobs_db = db::query_seal_task(pool).await?;

    let update = "update seal_task_detail set complete_time = sysdate(), task_status = 3 where task_id = ?";

    if jobs.is_empty() || jobs_db.is_empty(){
        return Ok(())
    }
    let mut job_map = HashMap::<u64, SealWork>::new();
    for (_, work) in jobs {
        for w in work {
            job_map.insert(w.sector.number, w);
        }
    }

    for w in &jobs_db {

        let job = job_map.get(&(w.sector_number as u64));
        if job.is_none() {
            let rows = sqlx::query(update).bind( &w.task_id).execute(pool).await?.rows_affected();
            println!("complete work {}, type {}, status {}, {}", w.task_id, w.task_type, w.task_status, rows);
        }
    }

    Ok(())
}